<template>
  <a-table
    :scroll="tableScroll"
    :style="{ width: '100%' }"
    :loading="loading"
    :columns="tableColumns"
    :data-source="dataList"
    :pagination="false"
    class="header-right-angle admin-table"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex == 'status'">
        {{ record.status }}
      </template>
      <template v-else-if="column.dataIndex == 'totalCallNum'"> {{ record.usedCallNum }}/{{ record.totalCallNum }} </template>
      <template v-else-if="column.dataIndex == 'operateMethodStatus'">
        <a-tooltip v-if="statusObj[record.operateMethodStatus].tooltip" placement="bottom">
          <template #title>
            <span>{{ record.operateMethodStatus?.substring(1) }}时间 {{ record?.operateMethodTime || '' }}</span>
          </template>
          {{ record.operateMethodStatus || '' }}
        </a-tooltip>
        <span v-else>{{ record.operateMethodStatus || '' }}</span>
      </template>
      <template v-else-if="column.dataIndex == 'appStatus'">
        <a-switch
          v-if="['可用', '禁用'].includes(record.appStatus)"
          :disabled="switchDisabled"
          :checked="record.appStatus"
          checked-value="可用"
          checked-children="可用"
          un-checked-value="禁用"
          un-checked-children="禁用"
          @change="(checked:any)=>changeAppStatus(checked,record.id)"
        />
        <template v-else>
          {{ record.appStatus }}
        </template>
      </template>
      <template v-else-if="column.dataIndex == 'time'"> {{ record.beforeValidTime }} ~ {{ record.afterValidTime }} </template>
      <template v-else>
        {{ replaceEmptyStr(record[column.dataIndex as string]) }}
      </template>
    </template>
  </a-table>
  <message-dialog
    v-model:show="showDisableModal"
    title="确认禁用"
    msg="此服务将会被禁止使用，请确认操作！"
    ok-text="确认并发送通知"
    :textarea-word-count="20"
    :textarea-show="false"
    @ok="disableClient"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { computed, inject, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import { checkKey } from '@/directives/auth'
  import { clientApi } from '@/services/api'
  import { replaceEmptyStr } from '@/utils'
  import { filterTableColumns } from '@/utils'

  import MessageDialog from '../MessageDialog.vue'

  export interface ApiItem {
    afterValidTime?: string
    algoName?: string
    appStatus?: string
    auditId?: number
    authTime?: string
    beforeValidTime?: string
    id?: string
    onlineId?: string
    operateMethodId?: string
    operateMethodStatus?: string
    operateMethodTime?: string
    qps?: number
    totalCallNum?: number
    usedCallNum?: number
    version?: string
  }

  const statusObj: any = {
    待删除: {
      name: '待删除',
      value: 0,
      background: 'rgba(25, 25, 48, 0.45)',
      color: 'rgba(25, 25, 48, 0.45)',
      tooltip: true
    },
    运行中: {
      name: '运行中',
      value: 1,
      background: 'rgba(55, 150, 137, 0.08)',
      color: 'rgba(55, 150, 137, 1)',
      tooltip: false
    },
    待启用: {
      name: '待启用',
      value: 2,
      background: 'rgba(92, 201, 105, 0.08)',
      color: 'rgba(92, 201, 105, 1)',
      tooltip: true
    },
    待停用: {
      name: '待停用',
      value: 3,
      background: 'rgba(245, 151, 0, 0.08)',
      color: 'rgba(245, 151, 0, 1)',
      tooltip: true
    },
    已停用: {
      name: '已停用',
      value: 4,
      background: 'rgba(214, 24, 96, 0.08)',
      color: 'rgba(214, 24, 96, 1)',
      tooltip: false
    },
    已删除: {
      name: '已删除',
      value: 4,
      background: 'rgba(214, 24, 96, 0.08)',
      color: 'rgba(214, 24, 96, 1)',
      tooltip: false
    }
  }

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: 'APICode',
        dataIndex: 'apiCode',
        width: 100
      },
      {
        title: '算法服务',
        dataIndex: 'algoName',
        width: 100
      },
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: '在线服务ID',
        dataIndex: 'onlineId',
        width: 100
      },
      {
        title: '调用量',
        dataIndex: 'totalCallNum',
        width: 100
      },
      {
        title: '算法运行状态',
        dataIndex: 'operateMethodStatus',
        width: 122
      },
      {
        title: '应用服务状态',
        dataIndex: 'appStatus',
        width: 122
      },
      {
        title: 'QPS',
        dataIndex: 'qps',
        width: 72
      },
      {
        title: '有效期',
        dataIndex: 'time',
        width: 310
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 180
      }
    ])
  )
  const tableScroll = computed(() => {
    const scrollX = tableColumns.value.reduce((prev, curr) => {
      return prev + (curr.width as number)
    }, 0)
    return {
      x: scrollX > 1022 ? scrollX : undefined,
      y: dataList.value.length >= 9 ? 510 : undefined
    }
  })

  const isAdmin = inject('isAdmin')
  const clientId = inject('clientId')

  const switchDisabled = computed(() => {
    if (isAdmin.value) {
      return !checkKey(['admin-list-api-disable'])
    } else {
      return !checkKey(['student-list-api-disable'])
    }
  })

  const { data, loading, runAsync: getDataList } = useRequest<ResponseData<any>>(clientApi.apiList)

  const dataList = computed<ApiItem[]>(() => {
    if (!data.value?.data) {
      return []
    }
    return data.value?.data
  })

  const currentDisableItem = ref<any>()
  const showDisableModal = ref(false)
  const changeAppStatus = async (checked: '可用' | '禁用', id: string) => {
    console.log(checked)
    if (checked === '可用') {
      await clientApi.openApi(id)({})
      getDataList({ uid: clientId })
      return
    } else {
      currentDisableItem.value = id
      showDisableModal.value = true
    }

    // Modal.confirm({
    //   title: ``,
    //   icon: createVNode(WarnIcon),
    //   content: '此服务将被禁止使用，请确认操作',
    //   okText: '确定',
    //   cancelText: '取消',
    //   centered: true,
    //   onOk: async () => {
    //     await clientApi.disableApi(id)({})
    //     getDataList({ uid: clientId })
    //   }
    // })
  }

  const disableClient = async () => {
    await clientApi.disableApi(currentDisableItem.value)({})
    // await clientApi.disableApi(id)({})
    message.success('操作成功')
    showDisableModal.value = false
    getDataList({ uid: clientId })
  }

  getDataList({ uid: clientId })
</script>
